package xyz.ranyh.jobclient;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewConfiguration;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.lang.reflect.Field;

import xyz.ranyh.jobclient.fragment.FavorityFragment;
import xyz.ranyh.jobclient.fragment.JobListFragment;
import xyz.ranyh.jobclient.fragment.UserFragment;

public class MainActivity extends BaseActivity implements View.OnClickListener,
        JobListFragment.OnFragmentInteractionListener,
        FavorityFragment.OnFragmentInteractionListener,
        UserFragment.OnFragmentInteractionListener {

    private LinearLayout jobsTab, starTab, userTab;
    private ImageButton mJobsTabButton, mStarTabButton, mUserTabButton;
    private TextView mJobsTabText, mStarTabText, mUserTabText;
    private FavorityFragment favorityFragment;
    private JobListFragment jobListFragment;
    private UserFragment userFragment;
    private FragmentManager fragmentManager;
    private Context context;
    private WebView webView = null;
    JobListFragment.WebViewListener webViewListener;
    private android.support.v7.app.ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        actionBar = getSupportActionBar();
        actionBar.setTitle(R.string.jobs_tab_title);
        actionBar.setCustomView(R.layout.action_bar);
        actionBar.getCustomView();

        initTab();
    }

    @Override
    protected void onStart() {
        super.onStart();
        initFragment();

        webViewListener = new JobListFragment.WebViewListener() {
            @SuppressLint("SetJavaScriptEnabled")
            @Override
            public void initWebView(String url, String title) {
                if (webView == null) {
                    webView = new WebView(MainActivity.this);
                    webView.setWebViewClient(new WebViewClient() {
                        //设置在webView点击打开的新网页在当前界面显示,而不跳转到新的浏览器中
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return true;
                        }
                    });
                    webView.getSettings().setJavaScriptEnabled(true);  //设置WebView属性,运行执行js脚本
                    webView.getSettings().setUseWideViewPort(true);
                    webView.getSettings().setLoadWithOverviewMode(true);
                    webView.getSettings().setBuiltInZoomControls(true);
                    webView.getSettings().setSupportZoom(true);
                    webView.loadUrl(url);          //调用loadUrl方法为WebView加入链接
                    MainActivity.this.setContentView(webView);
                } else {
                    webView.loadUrl(url);
                }
            }
        };
    }

    @Override
    public void onBackPressed() {
        if (webView != null) {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }
        } else {
            super.onBackPressed();
        }
    }

    private void initFragment() {
        fragmentManager = getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideAllFragment(transaction);
        jobListFragment = new JobListFragment();
        jobListFragment.setActionBar(actionBar);
        transaction.add(R.id.homePageFragment, jobListFragment);
//        jobListFragment.setWebViewListener(webViewListener);
        jobListFragment.setWebViewListener(new JobListFragment.WebViewListener() {
            @Override
            public void initWebView(String url, String title) {
                _initWebView(url, title);
            }
        });
        setIconOn(0);
        transaction.commit();
    }

    private void _initWebView(String url, String title) {
        if (webView == null) {
            webView = new WebView(MainActivity.this);
            webView.setWebViewClient(new WebViewClient() {
                //设置在webView点击打开的新网页在当前界面显示,而不跳转到新的浏览器中
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
            });
            webView.getSettings().setJavaScriptEnabled(true);  //设置WebView属性,运行执行js脚本
            webView.getSettings().setUseWideViewPort(true);
            webView.getSettings().setLoadWithOverviewMode(true);
            webView.loadUrl(url);          //调用loadUrl方法为WebView加入链接
            MainActivity.this.setContentView(webView);
            getSupportActionBar().setTitle(title);
        } else {
            webView.loadUrl(url);
        }
    }

    private void hideAllFragment(FragmentTransaction transaction) {
        if (jobListFragment != null) {
            transaction.hide(jobListFragment);
        }
        if (userFragment != null) {
            transaction.hide(userFragment);
        }
        if (favorityFragment != null) {
            transaction.hide(favorityFragment);
        }
    }

    private void initTab() {
        jobsTab = (LinearLayout) findViewById(R.id.jobs_tab);
        starTab = (LinearLayout) findViewById(R.id.star_tab);
        userTab = (LinearLayout) findViewById(R.id.user_tab);

        mJobsTabButton = (ImageButton) findViewById(R.id.jobs_tab_img);
        mStarTabButton = (ImageButton) findViewById(R.id.star_tab_img);
        mUserTabButton = (ImageButton) findViewById(R.id.user_tab_img);

        mJobsTabText = (TextView) findViewById(R.id.jobs_tab_text);
        mStarTabText = (TextView) findViewById(R.id.star_tab_text);
        mUserTabText = (TextView) findViewById(R.id.user_tab_text);

        jobsTab.setOnClickListener(this);
        starTab.setOnClickListener(this);
        userTab.setOnClickListener(this);

        resetTabs();
    }


    @Override
    public void onClick(View view) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideAllFragment(transaction);
        Log.d("active View", String.valueOf(view.getId()));
        switch (view.getId()) {
            case R.id.jobs_tab:
                setIconOn(0);
                if (jobListFragment == null) {
                    jobListFragment = new JobListFragment();
                    jobListFragment.setActionBar(actionBar);
                    transaction.add(R.id.homePageFragment, jobListFragment);
                    jobListFragment.setWebViewListener(webViewListener);
                } else {
                    transaction.show(jobListFragment);
                }
                getSupportActionBar().setTitle(R.string.jobs_tab_title);
                break;
            case R.id.star_tab:
                setIconOn(1);
                if (favorityFragment == null) {
                    favorityFragment = new FavorityFragment();
                    favorityFragment.setWebViewListener(new FavorityFragment.WebViewListener() {
                        @Override
                        public void initWebView(String url, String title) {
                            _initWebView(url, title);
                        }
                    });
                    transaction.add(R.id.homePageFragment, favorityFragment);
                } else {
                    transaction.show(favorityFragment);
                }
                getSupportActionBar().setTitle(R.string.star_tab_title);
                break;
            case R.id.user_tab:
                setIconOn(2);
                if (userFragment == null) {
                    userFragment = new UserFragment();
                    transaction.add(R.id.homePageFragment, userFragment);
                } else {
                    transaction.show(userFragment);
                }
                getSupportActionBar().setTitle(R.string.user_tab_title);
                break;
        }
        transaction.commit();
    }

    @TargetApi(Build.VERSION_CODES.M)
    private int getColorI(int id) {
        int color;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            color = getResources().getColor(id, null);
        } else {
            color = getResources().getColor(id);
        }

        return color;
    }

    private void resetTabs() {
        int color = getColorI(R.color.tabNoSelected);

        mJobsTabText.setTextColor(color);
        mStarTabText.setTextColor(color);
        mUserTabText.setTextColor(color);

        mJobsTabButton.setImageResource(R.drawable.home_deactive);
        mStarTabButton.setImageResource(R.drawable.followed_deactive);
        mUserTabButton.setImageResource(R.drawable.user_deactive);
    }

    private void setIconOn(int position) {
        resetTabs();
        int color = getColorI(R.color.tabSelected);
        switch (position) {
            case 0:
                mJobsTabText.setTextColor(color);
                mJobsTabButton.setImageResource(R.drawable.home_active);
                break;
            case 1:
                mStarTabText.setTextColor(color);
                mStarTabButton.setImageResource(R.drawable.followed_active);
                break;
            case 2:
                mUserTabText.setTextColor(color);
                mUserTabButton.setImageResource(R.drawable.user_active);
                break;
        }
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}
